﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace XCommunity.Documents
{
  public class DocumentService
  {

    public DocumentService( ICommunityContext context )
    {
      _context = context;
      _persister = new DocumentPersister( this );
      _cache = new DocumentCache();
    }


    /// <summary>
    /// 初始化服务
    /// </summary>
    public virtual void Init()
    {
      Cache.Init( Context.CacheService );
    }



    private DocumentPersister _persister;

    public DocumentPersister Persister
    {
      get { return _persister; }
    }



    private DocumentCache _cache;

    public DocumentCache Cache
    {
      get { return _cache; }
    }



    private ICommunityContext _context;

    public ICommunityContext Context
    {
      get { return _context; }
    }


    public void SaveDocument( Document document )
    {
      document.Meta.Author = Context.CurrentAccount.Name;

      Persister.SaveDocument( document );
      Cache.AddDocument( document );
    }

    public Document GetDocument( int documentId )
    {

      Document document = Cache.GetDocument( documentId );
      if ( document == null )
      {
        document = Persister.LoadDocument( documentId );
        Cache.AddDocument( document );
      }

      return document;
    }
  }
}
